package com.yc.weixin.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import com.yc.utils.StringUtil;

/**
 * 请求微信服务器的校验工具类
 * @author dengshuangjun
 *
 */
public class SignUtil {
	
	public static final String APPID="wx7e4e3566f6bbc5d5";
	
	public static final String APPSECRET="b1749ed2942981be57fee8b11fdb1e3b";
	
	/**
	 *  签名校验:
	 *  1. 将token、timestamp、nonce三个参数进行字典序排序,token来自用户填写服务注册信息自己填写的
		2. 将三个参数字符串拼接成一个字符串进行sha1加密
		3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	 * @param signature :   签名
	 * @param timestame :   时间戳
	 * @param nonce     : 	随机数
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	public static boolean checkSignature( String signature, String timestamp, String nonce) throws NoSuchAlgorithmException{
		if(  StringUtil.isBlank(signature) || StringUtil.isBlank(timestamp) || StringUtil.isBlank(nonce) ){
			return false;
		}
		String[] paramArrays=new String[]{WeixinbasicKey.TOKEN,timestamp, nonce};
		Arrays.sort(  paramArrays);
		String content=paramArrays[0].concat(  paramArrays[1]  ).concat(   paramArrays[2]);
		MessageDigest md=MessageDigest.getInstance("SHA-1");
		byte[] digest=md.digest(    content.toString().getBytes()  );
		String ciphertext = byteToString( digest );//将数组转成字符串
		return ciphertext!=null?ciphertext.equals(signature.toUpperCase()): false;
	}
	/**
	 * 将数组转成字符串
	 * @param digestByte
	 * @return
	 */
	private static String byteToString(byte[] digestByte) {
		StringBuffer   sb=new StringBuffer("");
		for(int i=0;i<digestByte.length;i++){
			sb.append(   byteToHexString(digestByte[i])  );
		}
		return sb.toString();
	}
/**
 * 将字节数组转成十六进制字符串
 * @param b
 * @return
 */
	private static Object byteToHexString(byte b) {
		char[] digit=new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		char[] tempArray=new char[2];
		tempArray[0]=digit[(b>>>4)&0x0F];
		tempArray[1]=digit[b&0x0f];
		
		String s=new String(   tempArray );
		return s;
	}
	
	
}
